package com.controller;

import com.alibaba.fastjson.JSON;
import com.entity.PostsEntity;
import com.service.PostsService;
import com.service.serviceImpl.PostsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/app/fatie")
public class FatieServlet extends HttpServlet {
    private PostsService postsService = new PostsServiceImpl();
    private Map<String, Object> responseMap = new HashMap<String, Object>();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String userId = session.getAttribute("userId").toString();
        BufferedReader reader = request.getReader();
        String params = reader.readLine();
        PostsEntity postsEntity = JSON.parseObject(params, PostsEntity.class);
        postsEntity.setReleaseTime(new Date());
        postsEntity.setLastTime(new Date());
        postsEntity.setUserId(userId);
        boolean b = postsService.insertPosts(postsEntity);
        if (b) {
            responseMap.put("flag", true);
            responseMap.put("msg", "发帖成功");
            String JSONMap = JSON.toJSONString(responseMap);
            response.getWriter().write(JSONMap);
        } else {
            responseMap.put("flag", false);
            responseMap.put("msg", "发帖失败");
            String JSONMap = JSON.toJSONString(responseMap);
            response.getWriter().write(JSONMap);
        }

    }
}
